package com.qf.controller;


import com.qf.common.core.domain.AjaxResult;
import com.qf.common.utils.poi.ExcelUtil;
import com.qf.domain.SysAttendance;
import com.qf.service.IMyAttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 普通用户考勤控制器
 * 接口路径：/system/attendance/my
 */
@RestController
@RequestMapping("/system/attendance/my")
public class MyAttendanceController {

    @Autowired
    private IMyAttendanceService attendanceService;

    /**
     * 普通用户：查询个人考勤列表
     * 权限标识：system:attendance:myList（需在 `sys_menu` 表配置）
     */
    @GetMapping("/list")
    public AjaxResult getMyAttendanceList(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        // 若未传日期，默认查询近30天
        if (startDate == null) {
            startDate = new Date(System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000);
        }
        if (endDate == null) {
            endDate = new Date();
        }
        List<SysAttendance> list = attendanceService.getMyAttendanceList(startDate, endDate);
        return AjaxResult.success().put("rows", list).put("total", list.size());
    }

    /**
     * 普通用户：上午打卡
     * 权限标识：system:attendance:myPunch（需在 `sys_menu` 表配置）
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:myPunch')")
    @PostMapping("/morning")
    public AjaxResult morningPunch(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date checkDate) {
        return attendanceService.morningPunch(checkDate);
    }

    /**
     * 普通用户：下午打卡
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:myPunch')")
    @PostMapping("/afternoon")
    public AjaxResult afternoonPunch(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date checkDate) {
        return attendanceService.afternoonPunch(checkDate);
    }

    /**
     * 普通用户：导出个人考勤数据（若依Excel工具类）
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:myExport')")
    @PostMapping("/export")
    public void exportAttendance(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        List<SysAttendance> list = attendanceService.getMyAttendanceList(startDate, endDate);
        ExcelUtil<SysAttendance> util = new ExcelUtil<>(SysAttendance.class);
        util.exportExcel(response, list, "个人考勤记录");
    }
}